import axios from "axios";
axios.defaults.baseURL = "/api";

function handleException(ex, callback) {
  let data = ex.response?.data;
  if (data) {
    const { code, message } = data;
    alert("状态编码：" + code + "\r\n错误消息：" + message, "a");
    try {
      callback({
        code,
        message,
        "data": {

        }
      });
    } catch (e) {
      alert(e);
    }
  } else {
    alert(ex);
  }

}


export function http_get(url, data, callback) {
  axios.get(url, {
    "method": "get",
    "params": data
  }).then(response => {
    if (callback) {
      callback(response.data);
    }
  }).catch(function (e) {
    handleException(e, callback);
  });
}

export function http_post(url, data, callback) {
  axios.post(url, data).then(response => {
    if (callback) {
      callback(response.data);
    }
  }).catch(function (e) {
    handleException(e, callback);
  });
}

export function renderView(params, callback) {
  http_get("/data/view", params, callback);
}

export default {
  get: http_get,
  post: http_post,
  renderView
}